<template>
	<dt-main-body v-model="labelPosition">
		<div class="location">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item>
					<i class="iconfont icon-home"></i>
					管理中心
				</el-breadcrumb-item>
				<el-breadcrumb-item>商城管理</el-breadcrumb-item>
				<el-breadcrumb-item>编辑商品</el-breadcrumb-item>
			</el-breadcrumb>
		</div>

		<div class="content-box">
			<el-form ref="editForm" :model="form" :rules="rules" :label-position="labelPosition" label-width="120px">
				<el-tabs v-model="activeName" type="card">
					<el-tab-pane label="基本信息" name="info">
						<div class="tab-content">
							<el-form-item label="是否上架">
								<el-switch :active-value="0" :inactive-value="1" v-model="form.model.status"></el-switch>
							</el-form-item>
							<el-form-item label="是否免运费">
								<el-switch :active-value="1" :inactive-value="0" v-model="form.model.isDeliveryFee"></el-switch>
							</el-form-item>
							<el-form-item label="选择类别">
								<dt-dropdown-check v-model="form.categoryCheckedNodes"
									:data="form.categoryList"
									:checked="form.categoryCheckedKeys">
								</dt-dropdown-check>
							</el-form-item>
							<el-form-item v-if="form.labelList" label="标签属性">
								<el-checkbox-group v-model="form.labelCheckedIds">
									<el-checkbox-button v-for="item in form.labelList"
										:key="item.id"
										:label="item.id">
										{{item.title}}
									</el-checkbox-button>
								</el-checkbox-group>
							</el-form-item>
							<el-form-item prop="model.brandId" label="选择品牌">
								<el-select v-model="form.model.brandId" placeholder="请选择...">
									<el-option v-for="item in form.brandList"
										:key="item.id"
										:label="item.title"
										:value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="model.title" label="商品标题">
								<el-input v-model="form.model.title" placeholder="必填，250字符内"></el-input>
							</el-form-item>
							<el-form-item prop="model.goodsNo" label="商品货号">
								<el-input v-model="form.model.goodsNo" placeholder="可空，不填写则自动生成"></el-input>
							</el-form-item>
							<el-form-item label="规格价格">
								<div class="form-flex">
									<el-select v-model="form.skuViewList" value-key="id" multiple
										placeholder="请选择已有规格" @change="handleCheckedSkuChange" class="grow">
										<el-option v-for="item in form.skuList" :key="item.id" :label="item.title+'（'+item.remark+'）'" :value="item"></el-option>
									</el-select>
									<dt-goods-sku @change="handleSkuAdd"></dt-goods-sku>
								</div>
								<el-table :data="form.skuViewList" :show-header="false" border class="table-form mat-20" v-if="form.skuViewList.length>0">
									<el-table-column width="110" prop="title" label="名称"></el-table-column>
									<el-table-column min-width="180" label="规格值">
										<template slot-scope="scope">
											<el-form-item>
												<el-checkbox-group v-model="form.skuCheckedKeys" @change="handleCheckedSkuChange">
													<el-checkbox v-for="(item,i) in scope.row.children" :key="item.id" :label="item.id">{{item.title}}</el-checkbox>
												</el-checkbox-group>
											</el-form-item>
										</template>
									</el-table-column>
								</el-table>
								<el-table :data="form.skuCheckedValues" border class="table-form mat-20" v-if="form.skuCheckedValues.length>0">
									<el-table-column min-width="100" label="货号">
										<template slot-scope="scope">
											<el-form-item :prop="'skuCheckedValues.'+scope.$index+'.goodsNo'" :rules='rules.goodsNo'>
												<el-input size="small" v-model="scope.row.goodsNo" placeholder="商品货号"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="90" label="库存数量">
										<template slot="header" slot-scope="scope">
											<div class="form-flex" @click="handleSetSkusAll('stockQuantity',handleStockChange)">
												<span class="grow">库存数量</span>
												<i class="icon el-icon-edit-outline"></i>
											</div>
										</template>
										<template slot-scope="scope">
											<el-form-item :prop="'skuCheckedValues.'+scope.$index+'.stockQuantity'" :rules='rules.stockQuantity'>
												<el-input size="small" v-model="scope.row.stockQuantity" @change="handleStockChange" placeholder="0件"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="80" label="市场价">
										<template slot="header" slot-scope="scope">
											<div class="form-flex" @click="handleSetSkusAll('marketPrice',handleMarketChange)">
												<span class="grow">市场价</span>
												<i class="icon el-icon-edit-outline"></i>
											</div>
										</template>
										<template slot-scope="scope">
											<el-form-item :prop="'skuCheckedValues.'+scope.$index+'.marketPrice'" :rules='rules.marketPrice'>
												<el-input size="small" v-model="scope.row.marketPrice" @change="handleMarketChange" placeholder="0.00元"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="80" label="销售价">
										<template slot="header" slot-scope="scope">
											<div class="form-flex" @click="handleSetSkusAll('sellPrice',handleSellChange)">
												<span class="grow">销售价</span>
												<i class="icon el-icon-edit-outline"></i>
											</div>
										</template>
										<template slot-scope="scope">
											<el-form-item :prop="'skuCheckedValues.'+scope.$index+'.sellPrice'" :rules='rules.sellPrice'>
												<el-input size="small" v-model="scope.row.sellPrice" @change="handleSellChange" placeholder="0.00元"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="80" label="成本价">
										<template slot="header" slot-scope="scope">
											<div class="form-flex" @click="handleSetSkusAll('costPrice',handleCostChange)">
												<span class="grow">成本价</span>
												<i class="icon el-icon-edit-outline"></i>
											</div>
										</template>
										<template slot-scope="scope">
											<el-form-item :prop="'skuCheckedValues.'+scope.$index+'.costPrice'" :rules='rules.costPrice'>
												<el-input size="small" v-model="scope.row.costPrice" @change="handleCostChange" placeholder="0.00元"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="80" label="重量(克)">
										<template slot="header" slot-scope="scope">
											<div class="form-flex" @click="handleSetSkusAll('weight',handleWeightChange)">
												<span class="grow">重量(克)</span>
												<i class="icon el-icon-edit-outline"></i>
											</div>
										</template>
										<template slot-scope="scope">
											<el-form-item :prop="'skuCheckedValues.'+scope.$index+'.weight'" :rules='rules.weight'>
												<el-input size="small" v-model="scope.row.weight" @change="handleWeightChange" placeholder="0克"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="80" label="起订量">
										<template slot="header" slot-scope="scope">
											<div class="form-flex" @click="handleSetSkusAll('minQuantity')">
												<span class="grow">起订量</span>
												<i class="icon el-icon-edit-outline"></i>
											</div>
										</template>
										<template slot-scope="scope">
											<el-form-item :prop="'skuCheckedValues.'+scope.$index+'.minQuantity'" :rules='rules.minQuantity'>
												<el-input size="small" v-model="scope.row.minQuantity" placeholder="0件"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="120" prop="skuText" label="规格描述"></el-table-column>
									<el-table-column fixed="right" width="80" label="设置" align="center">
										<template slot-scope="scope">
											<el-link :underline="false" icon="el-icon-edit-outline" @click="handlePriceOpen(scope.$index, scope.row.groupPrices)"></el-link>
											<el-link :underline="false" icon="el-icon-camera" @click="handleAlbumOpen(scope.$index, scope.row.imgUrl)"></el-link>
										</template>
									</el-table-column>
								</el-table>
							</el-form-item>
							<el-form-item label="商品参数">
								<div class="form-flex">
									<el-select v-model="form.model.fieldId" clearable @change="handleFieldChange" placeholder="请选择已有参数" class="grow">
										<el-option v-for="item in form.fieldList"
											:key="item.id"
											:label="item.title"
											:value="item.id">
										</el-option>
									</el-select>
									<dt-goods-field @change="handleFieldAdd"></dt-goods-field>
								</div>
								<el-table :data="form.fieldlOptions" :show-header="false" border class="table-form mat-20" v-if="form.fieldlOptions.length>0">
									<el-table-column width="110" prop="optionName" label="名称"></el-table-column>
									<el-table-column min-width="180" label="选项">
										<template slot-scope="scope">
											<el-form-item>
												<el-radio-group size="small" v-model="scope.row.optionValue" v-if="scope.row.controlType=='Radio'">
													<el-radio v-for="(item,i) in scope.row.itemOption.split(',')" :key="i" :label="item">{{item}}</el-radio>
												</el-radio-group>
												<el-checkbox-group size="small" v-model="scope.row.optionValue" v-if="scope.row.controlType=='CheckBox'">
													<el-checkbox v-for="(item,i) in scope.row.itemOption.split(',')" :key="i" :label="item">{{item}}</el-checkbox>
												</el-checkbox-group>
												<el-select size="small" v-model="scope.row.optionValue" placeholder="请选择" v-if="scope.row.controlType=='Select'">
													<el-option v-for="(item,i) in scope.row.itemOption.split(',')" :key="i" :value="item">{{item}}</el-option>
												</el-select>
												<el-input size="small" v-model="scope.row.optionValue" placeholder="可空，512字符内" v-if="scope.row.controlType=='Input'"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
								</el-table>
							</el-form-item>
							<el-form-item prop="model.unit" label="计件单位">
								<el-input v-model="form.model.unit" placeholder="必填，例如“件、台”，128字符内"></el-input>
							</el-form-item>
							<el-form-item prop="model.point" label="增加积分">
								<el-input v-model="form.model.point" placeholder="购买后赠送的会员积分"></el-input>
							</el-form-item>
							<el-form-item prop="model.exp" label="经验值">
								<el-input v-model="form.model.exp" placeholder="会员升级的经验值"></el-input>
							</el-form-item>
							<el-form-item prop="model.sortId" label="排序数字">
								<el-input v-model="form.model.sortId" placeholder="数字越小越排前"></el-input>
							</el-form-item>
							<el-form-item label="创建时间" v-if="form.model.id>0">
								{{form.model.addBy}} {{form.model.addTime}}
							</el-form-item>
							<el-form-item label="最后更新" v-if="form.model.id>0&&form.model.updateTime">
								{{form.model.updateBy}} {{form.model.updateTime}}
							</el-form-item>
						</div>
					</el-tab-pane>
					<el-tab-pane label="商品相册" name="albums">
						<div class="tab-content">
							<el-form-item prop="model.imgUrl" label="商品图片">
								<dt-upload v-model="form.model.imgUrl"></dt-upload>
							</el-form-item>
							<el-form-item label="商品相册">
								<dt-upload-album v-model="form.albumList" :twidth="300" :theight="300"></dt-upload-album>
							</el-form-item>
						</div>
					</el-tab-pane>
					<el-tab-pane label="商品介绍" name="details">
						<div class="tab-content">
							<el-form-item prop="model.subTitle" label="副标题">
								<el-input v-model="form.model.subTitle" placeholder="可空，512字符内"></el-input>
							</el-form-item>
							<el-form-item prop="model.keywords" label="关健字">
								<el-input v-model="form.model.keywords" placeholder="可空，以英文逗号分隔，512字符内"></el-input>
							</el-form-item>
							<el-form-item prop="model.zhaiyao" label="内容摘要">
								<el-input type="textarea" :rows="3" v-model="form.model.zhaiyao" show-word-limit maxlength="500"></el-input>
							</el-form-item>
							<el-form-item prop="model.content" label="商品介绍">
								<dt-editor v-model="form.model.content" placeholder="请输入商品描述"></dt-editor>
							</el-form-item>
						</div>
					</el-tab-pane>
				</el-tabs>
			</el-form>
		</div>

		<el-dialog title="会员组价格" @close="handlePriceClose" :destroy-on-close="true" :visible.sync="showPriceDialog" fullscreen>
			<el-form ref="priceForm" :model="form" :rules="rules" :label-position="labelPosition" label-width="120px">
				<el-form-item v-for="(item,index) in form.groupPriceList"
					:key="index"
					:label="item.title"
					:prop="'groupPriceList.'+index+'.price'"
					:rules="rules.price">
					<el-input v-model="item.price" placeholder="自定义的价格">
						<template slot="append">
							元，默认享受{{item.discount}}折优惠
						</template>
					</el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" icon="el-icon-edit" @click="submitPriceForm">确 定</el-button>
				<el-button type="warning" @click="showPriceDialog = false">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog title="关联相册图片" @close="handleAlbumClose" :destroy-on-close="true" :visible.sync="showAlbumDialog" fullscreen>
			<div class="album-list">
				<div class="list-box" v-for="item in form.albumList" @click="showAlbumImgUrl=item.thumbPath">
					<div :class="showAlbumImgUrl==item.thumbPath?'img-box selected':'img-box'">
						<img :src="$api.loadFile(item.thumbPath)" />
					</div>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" icon="el-icon-edit" @click="handleAlbumConfirm">确 定</el-button>
				<el-button type="warning" icon="el-icon-remove-outline" @click="handleAlbumCancel">清 除</el-button>
			</div>
		</el-dialog>
		
		<div class="footer-box">
			<div class="footer-btn">
				<el-button type="primary" :loading="loading" @click="submitForm">确认保存</el-button>
				<el-button plain @click="$common.back()">返回上一页</el-button>
			</div>
		</div>
	</dt-main-body>
</template>

<script>
	import DtDropdownCheck from '../../../components/DtDropdownCheck.vue'
	import DtUpload from '../../../components/DtUpload.vue'
	import DtUploadAlbum from '../../../components/DtUploadAlbum.vue'
	import DtEditor from '../../../components/DtEditor.vue'
	import DtGoodsField from '../../../components/DtGoodsField.vue'
	import DtGoodsSku from '../../../components/DtGoodsSku.vue'
	
	export default {
		components: {
			DtDropdownCheck,
			DtUpload,
			DtUploadAlbum,
			DtEditor,
			DtGoodsField,
			DtGoodsSku
		},
		props: {
			id: 0
		},
		data() {
			return {
				activeName: 'info', //当前选项卡
				labelPosition: 'right', //表单对齐方式
				loading: false,
				showPriceDialog: false,//会员组价格显示状态
				showPriceIndex: -1,//会员组价格显示索引
				showAlbumDialog: false,//商品相册显示状态
				showAlbumIndex: -1,//商品SKU的索引
				showAlbumImgUrl: null,//商品SKU关联图片
				//表单数据
				form: {
					categoryList: [],//类别列表
					categoryCheckedKeys: [],//初始化选中健，修改赋值
					categoryCheckedNodes: [],//当前选中类别节点,保存取值
					brandList: [],//品牌列表
					labelList: [],//标签列表
					labelCheckedIds: [],//标签选中值,保存取值
					skuList: [],//规格列表
					skuViewList: [], //规格显示列表
					skuCheckedList: [],//规格父子列表,保存取值
					skuCheckedKeys: [],//规格选中ID,修改赋值
					skuCheckedValues: [],//规格选中值,保存取值
					fieldList: [],//模型列表
					fieldlOptions: [],//当前模型选项列表,保存取值
					memberGroupList: [],//会员组列表
					groupPriceList: [],//会员组价格列表
					albumList: [],//相册列表,修改赋值,保存取值
					//商品信息
					model: {
						id: 0,
						addBy: null,
						addTime: null,
						updateBy: null,
						updateTime: null,
						upTime: null,
						click: 0,
						evaluateCount: 0,
						favoriteCount: 0,
						saleCount: 0,
						categoryTitle: null,
						labelTitle: null,
						brandTitle: null,
						merchantTitle: null,
						merchantId: 0,
						brandId: null,
						fieldId: null,
						callIndex: null,
						title: null,
						subTitle: null,
						keywords: null,
						goodsNo: null,
						stockQuantity: 0,
						marketPrice: 0,
						sellPrice: 0,
						costPrice: 0,
						weight: 0,
						unit: '件',
						point: 0,
						exp: 0,
						imgUrl: null,
						zhaiyao: null,
						content: null,
						sortId: 99,
						isDeliveryFee: 0,
						status: 0,
						fieldValues: [],
						categoryRelations: [],
						labelRelations: [],
						goodsProducts: [],
						goodsSkus: [],
						goodsAlbums: []
					}
				},
				//验证规则
				rules: {
					model: {
						brandId: [
							{ required: true, message: '请选择商品品牌', trigger: 'change' }
						],
						title: [
							{ required: true, message: '请输入商品标题', trigger: 'blur' }
						],
						sortId: [
							{ required: true, message: '请输入排序数字', trigger: 'blur' }
						],
						content: [
							{ required: true, message: '请输入商品介绍', trigger: 'blur' }
						],
						goodsNo: [
							{ required: true, message: '请输入商品货号', trigger: 'blur' }
						],
						unit: [
							{ required: true, message: '请输入商品计件单位', trigger: 'blur' }
						],
						point: [
							{ required: true, message: '请输入赠送积分', trigger: 'blur' },
							{ pattern: /^-?[0-9]\d*$/, message: '积分只能为整数', trigger: 'blur' }
						],
						exp: [
							{ required: true, message: '请输入赠送经验值', trigger: 'blur' },
							{ pattern: /^-?[0-9]\d*$/, message: '经验值只能为整数', trigger: 'blur' }
						]
					},
					goodsNo: [
						{ required: true, message: '请输入商品货号', trigger: 'blur' }
					],
					stockQuantity: [
						{ required: true, message: '请填写库存数量', trigger: 'blur' },
						{ pattern: /^-?[0-9]\d*$/, message: '库存数量只能为整数', trigger: 'blur' }
					],
					minQuantity: [
						{ required: true, message: '请填写最小购买数量', trigger: 'blur' },
						{ pattern: /^-?[0-9]\d*$/, message: '起订数量只能为整数', trigger: 'blur' }
					],
					marketPrice: [
						{ required: true, message: '请填写市场价', trigger: 'blur' },
						{ pattern: /(^-?[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '只能填写金额格式', trigger: 'blur' }
					],
					sellPrice: [
						{ required: true, message: '请填写销售价', trigger: 'blur' },
						{ pattern: /(^-?[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '只能填写金额格式', trigger: 'blur' }
					],
					costPrice: [
						{ required: true, message: '请填写成本价', trigger: 'blur' },
						{ pattern: /(^-?[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '只能填写金额格式', trigger: 'blur' }
					],
					weight: [
						{ required: true, message: '请填写重量', trigger: 'blur' },
						{ pattern: /^-?[0-9]\d*$/, message: '重量只能为整数', trigger: 'blur' }
					],
					price: [
						{ required: true, message: '请填写价格', trigger: 'blur' },
						{ pattern: /(^-?[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '只能填写金额格式', trigger: 'blur' }
					],
				},
			}
		},
		methods: {
			//初始化数据
			initData() {
				let _this = this; //当前页面
				if (_this.id) {
					_this.$api.request({
						url: '/merchant/shop/goods/' + _this.id,
						loading: true,
						success(res) {
							//赋值给model
							Object.keys(_this.form.model).forEach(key => { _this.form.model[key] = res.data[key] });
							//如果0则将该字段设置为null
							_this.form.model.fieldId = _this.form.model.fieldId == 0 ? null : _this.form.model.fieldId;
							//给标签选中赋值
							if (_this.form.model.labelRelations) {
								_this.form.model.labelRelations.map(item => {
									_this.form.labelCheckedIds.push(item.labelId);
								});
							}
							//给类别设置选中赋值
							if (_this.form.model.categoryRelations) {
								let categoryIds = [];
								_this.form.model.categoryRelations.map(item => {
									categoryIds.push(item.categoryId);
								});
								_this.form.categoryCheckedKeys = categoryIds;
							}
							//商品模型设置选中值
							_this.handleFieldChange(_this.form.model.fieldId);//回调处理
							//商品规格赋值
							if (_this.form.model.goodsSkus) {
								let skuIds = [];
								let parentIds = [];
								_this.form.model.goodsSkus.map(item => {
									if (item.parentId > 0) {
										skuIds.push(item.skuId);
									}
									if(item.parentId == 0) {
										parentIds.push(item.skuId);
									}
								});
								_this.form.skuCheckedKeys = skuIds;
								//查找出父规格赋值给显示规格，严格排序禁用filter
								//_this.form.skuViewList = _this.form.skuList.filter(item => parentIds.includes(item.id));
								parentIds.map(pid => {
									let pitem = _this.form.skuList.find(item => item.id === pid)
									if(pitem != null) _this.form.skuViewList.push(pitem)
								});
								_this.handleCheckedSkuChange();//回调处理
							}
							//相册赋值
							if (_this.form.model.goodsAlbums) {
								_this.form.model.goodsAlbums.map(function (item) {
									item.url = item.thumbPath;
									_this.form.albumList.push(item);
								})
							}
						}
					});
				} else {
					//默认选中第一个品牌
					if(_this.form.brandList.length > 0){
						_this.form.model.brandId = _this.form.brandList[0].id;
					}
				}
			},
			//初始化控件
			async initLoad() {
				let _this = this;
				//加载分类列表
				await _this.$api.request({
					url: '/client/shop/category',
					success(res) {
						_this.form.categoryList = res.data
					}
				});
				//加载品牌列表
				await _this.$api.request({
					url: '/client/shop/brand/view/0?status=0',
					success(res) {
						_this.form.brandList = res.data;
					}
				});
				//加载标签列表
				await _this.$api.request({
					url: '/client/shop/label/view/0?status=0',
					success(res) {
						_this.form.labelList = res.data;
					}
				});
				//加载规格列表
				await _this.$api.request({
					url: '/merchant/shop/sku/view/0',
					success(res) {
						_this.form.skuList = res.data;
					}
				});
				//加载模型列表
				await _this.$api.request({
					url: '/merchant/shop/field/view/0',
					success(res) {
						_this.form.fieldList = res.data;
					}
				});
				//加载会员组列表
				await _this.$api.request({
					url: '/merchant/member/group/view/0',
					success(res) {
						_this.form.memberGroupList = res.data;
					}
				});
				//初始化数据
				this.initData();
			},
			//提交表单
			submitForm() {
				let _this = this; //当前页面
				//多个表单验证
				const f1 = new Promise((resolve, reject) => {
					_this.$refs['editForm'].validate((valid) => {
						if (valid) resolve()
					});
				});
				Promise.all([f1]).then(() => {
					//检查及组合参数
					if (_this.form.categoryCheckedNodes.length === 0) {
						_this.$message({ type: 'warning', message: '错误提示：请选择商品类别' });
						return false;
					}
					if (_this.form.skuCheckedValues.length === 0) {
						_this.$message({ type: 'warning', message: '错误提示：请选择商品规格' });
						return false;
					}

					//分类取值
					let categoryRelations = [];
					_this.form.categoryCheckedNodes.map(function (item) {
						let modelt = {
							id: 0,
							goodsId: _this.form.model.id,
							categoryId: item.id
						}
						//遍历Model已有值，防止ID丢失
						_this.form.model.categoryRelations.map(function (v) {
							if (modelt.categoryId === v.categoryId) {
								modelt.id = v.id;
							}
						});
						categoryRelations.push(modelt);
					});
					_this.form.model.categoryRelations = categoryRelations;

					//标签取值
					let labelRelations = [];
					_this.form.labelCheckedIds.map(function (id) {
						let modelt = {
							id: 0,
							goodsId: _this.form.model.id,
							labelId: id
						}
						//遍历Model已有值，防止ID丢失
						_this.form.model.labelRelations.map(function (v) {
							if (modelt.labelId === v.labelId) {
								modelt.id = v.id;
							}
						});
						labelRelations.push(modelt);
					});
					_this.form.model.labelRelations = labelRelations;
					//扩展属性取值
					_this.form.fieldlOptions.forEach(item => {
						if (item.controlType == 'CheckBox') {
							item.optionValue = item.optionValue.toString();
						}
					});
					_this.form.model.fieldValues = _this.form.fieldlOptions;
					//商品货品取值
					_this.form.model.goodsProducts = _this.form.skuCheckedValues;
					//商品规格列表取值
					_this.form.model.goodsSkus = _this.form.skuCheckedList;
					//相册取值
					let albumList = [];
					_this.form.albumList.map(function (item) {
						albumList.push({
							id: item.id,
							goodsId: _this.form.model.id,
							thumbPath: item.thumbPath,
							originalPath: item.originalPath,
							remark: item.remark,
							sortId: item.sortId
						});
					})
					_this.form.model.goodsAlbums = albumList;
					//提交表单,Id大于0则修改，否则添加
					if (_this.form.model.id > 0) {
						_this.$api.request({
							method: 'put',
							url: '/merchant/shop/goods/' + _this.form.model.id,
							data: _this.form.model,
							successMsg: '修改商品已成功',
							beforeSend() {
								_this.loading = true
							},
							success(res) {
								//可跳转加列表页
								_this.$common.linkUrl('/shop/goods/list');
							},
							complete() {
								_this.loading = false
							}
						});
					} else {
						_this.$api.request({
							method: 'post',
							url: '/merchant/shop/goods',
							data: _this.form.model,
							successMsg: '新增商品已成功',
							beforeSend() {
								_this.loading = true
							},
							success(res) {
								//重置表单
								_this.$refs['editForm'].resetFields();
							},
							complete() {
								_this.loading = false
							}
						});
					}
				})
			},
			//选择商品参数回调
			handleFieldChange(val) {
				let _this = this; //当前页面
				let optionList = []; //选项列表
				let valueList = []; //选项值列表
				//取得扩展模型字段列表
				_this.form.fieldList.map((item) => {
					if (item.id == val)
						optionList = item.options;
				});
				//扩展模型字段列表赋值
				optionList.map(function (item) {
					let obj = {
						id: 0,
						goodsId: 0,
						optionId: item.id,
						optionName: item.name,
						optionValue: item.controlType == 'CheckBox' ? [] : null,
						controlType: item.controlType,
						itemOption: item.itemOption
					};
					//给已存在的商品模型赋值
					if (_this.form.model.fieldValues) {
						_this.form.model.fieldValues.map((v) => {
							if (v.optionId === item.id) {
								obj.id = v.id;
								obj.goodsId = v.goodsId;
								if (item.controlType == 'CheckBox')
									obj.optionValue = v.optionValue.split(",");
								else
									obj.optionValue = v.optionValue;
							}
						});
					}
					valueList.push(obj);
				});
				_this.form.fieldlOptions = valueList;
			},
			//添加商品参数回调
			handleFieldAdd(val) {
				//赋值给列表
				this.form.fieldList.push(val);
				//设置为默认选中
				this.form.model.fieldId = val.id;
				this.handleFieldChange(val.id);
			},
			//添加商品规格回调
			handleSkuAdd(val) {
				//赋值给列表
				this.form.skuList.push(val);
				//设置为默认选中
				this.form.skuViewList.push(val);
				this.handleCheckedSkuChange();
			},
			//商品规格回调
			handleCheckedSkuChange() {
				let _this = this;
				let skuParentIds = [];//选中的父规格数组
				let skuCheckedList = [];//选中的规格父子列表
				let skuCheckedChildren = [];//选中的规格子列表
				//根据规格ID找到列表
				_this.form.skuViewList.map(function (item) {
					if (item.children) {
						let hasParent = false; //是否已存在父规格
						item.children.map(function (citem) {
							_this.form.skuCheckedKeys.map(function (id) {
								if (citem.id === id) {
									//检查是否已添加父规格
									if (!hasParent) {
										skuParentIds.push(item.id);
										skuCheckedList.push({
											id: 0,
											goodsId: _this.form.model.id,
											skuId: item.id,
											parentId: 0,
											title: item.title,
											imgUrl: item.imgUrl
										});
										hasParent = true;
									}
									//暂存父子规格列表
									skuCheckedChildren.push(citem);
									skuCheckedList.push({
										id: 0,
										goodsId: _this.form.model.id,
										skuId: citem.id,
										parentId: citem.parentId,
										title: citem.title,
										imgUrl: citem.imgUrl
									});
								}
							});
						});
					}
				});
				//将规格子列表进行分组
				let skuArrValue = [];//规格分组数组
				skuParentIds.map(function (id, index) {
					skuArrValue.push([]);
					skuCheckedChildren.map(function (item) {
						if (item.parentId == id) {
							skuArrValue[index].push(item);
						}
					});
				});
				//生成笛卡尔值列表
				let skuValueList = [];
				let descSkuList = _this.calcDescartes(skuArrValue);//返回笛卡尔值
				if (typeof (_this.form.model.goodsNo) != 'string' || _this.form.model.goodsNo == '') {
					_this.form.model.goodsNo = 'GN' + _this.mathRandGoodNo(10);//随机生成货号
				}
				for (var i = 0; i < descSkuList.length; i++) {
					let skuTitle = [];
					let skuIds = [];
					if (descSkuList[i] instanceof Array) {
						descSkuList[i].map(function (item) {
							skuTitle.push(item.title);
							skuIds.push(item.id);
						});
					} else {
						skuTitle.push(descSkuList[i].title);
						skuIds.push(descSkuList[i].id);
					}
					let skuTemp = {
						id: 0,
						goodsId: _this.form.model.id,
						goodsNo: _this.form.model.goodsNo + '-' + (i + 1),
						stockQuantity: null,
						marketPrice: null,
						sellPrice: null,
						costPrice: null,
						weight: null,
						minQuantity: null,
						skuIds: skuIds.toString(),
						skuText: skuTitle.toString(),
						imgUrl: null,
						groupPrices: []
					}
					//检查商品规格列表是否有值
					_this.form.model.goodsProducts.map(function (item) {
						if (item.goodsId === skuTemp.goodsId && item.skuIds == skuTemp.skuIds) {
							skuTemp = item;
						}
					});
					skuValueList.push(skuTemp);
				}
				_this.form.skuCheckedList = skuCheckedList;
				_this.form.skuCheckedValues = skuValueList;
			},
			//笛卡尔值计算
			calcDescartes(array) {
				if (array.length < 2) return array[0] || [];
				return [].reduce.call(array, function (col, set) {
					var res = [];
					col.forEach(function (c) {
						set.forEach(function (s) {
							var t = [].concat(Array.isArray(c) ? c : [c]);
							t.push(s);
							res.push(t);
						})
					});
					return res;
				});
			},
			//随机生成货号
			mathRandGoodNo(n) {
				var Num = '';
				for (var i = 0; i < n; i++) {
					Num += Math.floor(Math.random() * 10);
				}
				return Num;
			},
			//库存数量回调
			handleStockChange() {
				let _this = this;
				_this.form.model.stockQuantity = _this.form.skuCheckedValues.reduce(function (total, item) {
					if (!isNaN(parseInt(item.stockQuantity))) {
						return total + parseInt(item.stockQuantity);
					}
					return total;
				}, 0);
			},
			//市场价回调
			handleMarketChange() {
				let _this = this;
				let minPrice = Math.min.apply(Math, _this.form.skuCheckedValues.map((item) => {
					let price = parseFloat(item.marketPrice);
					if (!isNaN(price)) {
						return price;
					}
					return 0;
				}));
				_this.form.model.marketPrice = minPrice;
				//console.log(minPrice)
			},
			//销售价回调
			handleSellChange() {
				let _this = this;
				let minPrice = Math.min.apply(Math, _this.form.skuCheckedValues.map((item) => {
					let price = parseFloat(item.sellPrice);
					if (!isNaN(price)) {
						return price;
					}
					return 0;
				}));
				_this.form.model.sellPrice = minPrice;
				//console.log('最小销售价：' + _this.form.model.sellPrice)
			},
			//成本价回调
			handleCostChange() {
				let _this = this;
				let minPrice = Math.min.apply(Math, _this.form.skuCheckedValues.map((item) => {
					let price = parseFloat(item.costPrice);
					if (!isNaN(price)) {
						return price;
					}
					return 0;
				}));
				_this.form.model.costPrice = minPrice;
				//console.log('最小成本价：' + _this.form.model.costPrice)
			},
			//重量回调
			handleWeightChange() {
				let _this = this;
				_this.form.model.weight = _this.form.skuCheckedValues.reduce(function (total, item) {
					if (!isNaN(parseInt(item.weight))) {
						return total + parseInt(item.weight);
					}
					return total;
				}, 0);
				//console.log(_this.form.model.weight);
			},
			//会员组价格设置
			handlePriceOpen(i, list) {
				let _this = this;
				_this.form.memberGroupList.map(function (group) {
					let modelt = {
						id: 0,
						groupId: group.id,
						productId: 0,
						price: null,
						title: group.title,
						discount: group.discount
					}
					if (list && list.length > 0) {
						list.map(function (item) {
							if (item.groupId == group.id) {
								modelt.id = item.id;
								modelt.productId = item.productId;
								modelt.price = item.price;
							}
						});
					}
					_this.form.groupPriceList.push(modelt);
				});
				_this.showPriceIndex = i;
				_this.showPriceDialog = true;
			},
			//会员组价格关闭回调
			handlePriceClose() {
				this.showPriceIndex = -1;
				this.form.groupPriceList = [];
			},
			//会员组价格提交
			submitPriceForm() {
				let _this = this; //当前页面
				//表单验证
				_this.$refs['priceForm'].validate((valid) => {
					if (valid) {
						let groupPriceTemp = [];
						_this.form.groupPriceList.map(function (item) {
							let modelt = {
								id: item.id,
								groupId: item.groupId,
								productId: item.productId,
								price: item.price
							}
							groupPriceTemp.push(modelt);
						});
						//赋值给商品规格所在项
						_this.form.skuCheckedValues[_this.showPriceIndex].groupPrices = groupPriceTemp;
						_this.showPriceDialog = false;
					} else {
						return false;
					}
				});
			},
			//关联相册设置
			handleAlbumOpen(i, val) {
				let _this = this;
				if (_this.form.albumList.length == 0) {
					_this.$message({ type: 'warning', message: '请先上传相册再关联' });
					return false;
				}
				_this.showAlbumIndex = i;
				_this.showAlbumImgUrl = val;
				_this.showAlbumDialog = true;
			},
			//相册关闭回调
			handleAlbumClose() {
				this.showAlbumIndex = -1;
				this.showAlbumImgUrl = null;
			},
			//相册确认关联
			handleAlbumConfirm() {
				let _this = this;
				if (_this.showAlbumIndex == -1 || !_this.showAlbumImgUrl) {
					_this.$message({ type: 'warning', message: '请选择相册图片再提交' });
					return false;
				}
				//赋值给商品规格所在项
				_this.form.skuCheckedValues[_this.showAlbumIndex].imgUrl = _this.showAlbumImgUrl;
				_this.showAlbumDialog = false;
			},
			//相册取消关联
			handleAlbumCancel() {
				//赋值给商品规格所在项
				this.form.skuCheckedValues[this.showAlbumIndex].imgUrl = null;
				this.showAlbumDialog = false;
			},
			//统一价格规格数量
			handleSetSkusAll(attrName, callback) {
				let _this = this;
				//设置弹窗
				_this.$prompt('请输入数值', '统一设置', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					inputPattern:  /^[0-9]+(.[0-9]{1,2})?$/,
					inputErrorMessage: '数值格式不正确',
				}).then(({ value }) => {
					_this.form.skuCheckedValues.forEach(item => {
						if(typeof(item[attrName]) != 'undefined')
							item[attrName] = value;
					});
					//调用回调函数
					if (typeof callback === 'function') callback();
				}).catch(() => {});
			},
		},
		created() {
			//初始化控件
			this.initLoad();
		}
	}
</script>

<style lang="scss">
	.form-flex {
		display: flex;
		justify-content: space-between;
		align-items: center;
		.grow {
			flex-grow: 1;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
		.icon {
			cursor: pointer;
		}
	}
</style>